using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections.Specialized;
using System.Web;

namespace Husb.Data
{
    public static class AppContext
    {
        #region Logical Execution Location

        public enum LogicalExecutionLocations
        {
            Client,
            Server
        }
        private static LogicalExecutionLocations _logicalExecutionLocation = LogicalExecutionLocations.Client;
        public static LogicalExecutionLocations LogicalExecutionLocation
        {
            get { return _logicalExecutionLocation; }
        }

        internal static void SetLogicalExecutionLocation(LogicalExecutionLocations location)
        {
            _logicalExecutionLocation = location;
        }

        #endregion

        #region Client/Global Context

        private static object _syncClientContext = new object();
        private const string _clientContextName = "Husb.ClientContext";
        private const string _globalContextName = "Husb.GlobalContext";

        // internal
        public static void SetGlobalContext(HybridDictionary globalContext)
        {
#if !CLIENTONLY
            if (HttpContext.Current == null)
            {
#endif
                LocalDataStoreSlot slot = Thread.GetNamedDataSlot(_globalContextName);
                Thread.SetData(slot, globalContext);
#if !CLIENTONLY
            }
            else
                HttpContext.Current.Items[_globalContextName] = globalContext;
#endif
        }
        // internal
        public static HybridDictionary GetGlobalContext()
        {
#if !CLIENTONLY
            if (HttpContext.Current == null)
            {
#endif
                LocalDataStoreSlot slot = Thread.GetNamedDataSlot(_globalContextName);
                return (HybridDictionary)Thread.GetData(slot);
#if !CLIENTONLY
            }
            else
                return (HybridDictionary)HttpContext.Current.Items[_globalContextName];
#endif
        }

        public static HybridDictionary GlobalContext
        {
            get
            {
                HybridDictionary ctx = GetGlobalContext();
                if (ctx == null)
                {
                    ctx = new HybridDictionary();
                    SetGlobalContext(ctx);
                }
                return ctx;
            }
        }

        #endregion
    }
}
